<template>
  <el-row>
    <div class="mb8" style="width: 100%;display: flex;flex-direction: row">
      <el-upload
          v-model:file-list="fileList"
          :action="createAction()"
          multiple
          :headers="{'Authorization':`Bearer ${token}`}"
          :show-file-list="false"
          :on-success="uploadSuccess"
      >
        <el-button type="success" icon="upload" :disabled="uploadDisabled">{{ $t('qms.clickToUpload') }}</el-button>
      </el-upload>
      <el-button :disabled="multiple" icon="Delete" type="danger" @click="handleDelete(selectObjs)"
                 style="margin-left: 10px">
        {{ $t('btn.delete') }}
      </el-button>
    </div>
  </el-row>
  <el-table :data="state.dataList" v-loading="state.loading" border
            highlight-current-row
            :cell-style="tableStyle.cellStyle" :header-cell-style="tableStyle.headerCellStyle"
            @selection-change="selectionChangHandle"
            @sort-change="sortChangeHandle">
    <el-table-column type="selection" width="40" align="center"/>
    <el-table-column type="index" label="#" width="40"/>
    <el-table-column prop="name" :label="$t('qms.fileName')" show-overflow-tooltip/>
    <el-table-column prop="size" :label="$t('qms.fileSize')" show-overflow-tooltip>
      <template #default="scope">
        {{
          bytesToSize(scope.row.size)
        }}
      </template>
    </el-table-column>
    <el-table-column prop="creator" :label="$t('sop.uplink')" show-overflow-tooltip/>
    <el-table-column prop="createTime" :label="$t('sop.uploadTime')" show-overflow-tooltip/>
    <el-table-column :label="$t('operation.Operation')" width="150">
      <template #default="scope">
        <el-button icon="view" type="info" plain
                   @click="preview(scope.row)">
        </el-button>
        <el-button icon="download" type="primary"
                   @click="downLoad(scope.row)">
        </el-button>

      </template>
    </el-table-column>
  </el-table>
  <pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" v-bind="state.pagination"/>

</template>

<script setup lang="ts" name="systemSysFile">
import {BasicTableProps, useTable} from "/@/hooks/table";
import {fetchList, delObjs} from "/@/api/platform/mes/sysFile";
import {useMessage, useMessageBox} from "/@/hooks/message";
import {Session} from "/@/utils/storage";
import {Base64} from 'js-base64';
import {downBlobFile} from "/@/utils/other";
import {useI18n} from "vue-i18n";

const {t} = useI18n();


// 定义查询字典

// 定义变量内容
const formDialogRef = ref()
// 搜索变量
const queryRef = ref()
// 多选变量
const selectObjs = ref([]) as any
const multiple = ref(true)
const uploadDisabled = ref(true)
const fileList = ref([])

const state: BasicTableProps = reactive<BasicTableProps>({
  queryForm: {},
  pageList: fetchList
})

const uploadSuccess = () => {
  getDataList();
}

// 父级点击的行
const parentClickRow = ref({})
const token = ref(Session.getToken())

const createAction = () => {
  return '/api/eletile-mes/sysFile/upload?id=' + parentClickRow.value.uuid
}

const bytesToSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(2)} ${sizes[i]}`;
}


//  table hook
const {
  getDataList,
  currentChangeHandle,
  sizeChangeHandle,
  sortChangeHandle,
  tableStyle
} = useTable(state)

// 清空搜索条件
const resetQuery = () => {
  // 清空搜索条件
  queryRef.value?.resetFields()
  // 清空多选
  selectObjs.value = []
  getDataList()
}

const preview = (row) => {
  window.open("http://172.16.100.10:8012" + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(row.url)));
}
const downLoad = (row) => {
  downBlobFile(row.url, null, row.name)
}


// 通过id进行子表的查询
const query = (row: Object) => {
  // 赋值查询参数
  state.queryForm.bizId = row.uuid
  // 保存选中的行数据
  parentClickRow.value.uuid = row.uuid
  uploadDisabled.value = false
  // 刷新子表数据
  getDataList()
}

// 多选事件
const selectionChangHandle = (objs: { uuid: string }[]) => {
  selectObjs.value = objs.map(({uuid}) => uuid);
  multiple.value = !objs.length;
};

// 删除操作
const handleDelete = async (ids: string[]) => {
  try {
    await useMessageBox().confirm(t('operation.permanentDeletion'));
  } catch {
    return;
  }

  try {
    await delObjs(ids);
    getDataList();
    useMessage().success(t('qms.Successful'));
  } catch (err: any) {
    useMessage().error(err.msg);
  }
};
// 暴露变量
defineExpose({
  query
});


</script>
